import { _decorator, Component, director, Node, ProgressBar, SceneAsset, Sprite, spriteAssembler } from 'cc';
import { ClientAPI } from '../src/api/client.api';
import { LocalStorageMgr } from './LocalStorageMgr';
import { NCPoint } from '../src/api/api.config.client';
import GlobalData from './GlobalData';
const { ccclass, property } = _decorator;

@ccclass('Loading')
export class Loading extends Component {

    @property(Node)
    button: Node = null;
    @property(Sprite)
    private progressBar: Sprite = null;
    fakeProgress: number;


    start() {
        ClientAPI.CloseLoading();
    }

    update(deltaTime: number) {

    }

    loadScene(sceneName: string): void {
        if (!LocalStorageMgr.getItem(LocalStorageMgr.gameInitFinish_key)) {
            ClientAPI.Point(NCPoint.GAMEINITSTART, { userid: GlobalData.userId });
        }
        // 预加载场景
        director.preloadScene(sceneName, this.onProgress.bind(this), (err, sceneAsset: SceneAsset) => {
            if (err) {
                console.error(`Failed to load scene: ${sceneName}`, err);
                return;
            }
            // 当场景实际加载完成后，将假的进度条快速补满到100%
            this.fakeProgress = 1;
            // 延迟一小段时间以展示进度条达到100%的效果
            this.scheduleOnce(() => {
                // 加载完成，切换场景
                director.loadScene(sceneName, (err) => {
                    if (err) {
                        console.error(`Failed to switch to scene: ${sceneName}`, err);
                    } else {
                        console.log(`Scene ${sceneName} loaded successfully!`);
                    }
                });

            }, 0.1); // 这里延迟0.5秒后切换场景
        });

        // 初始化假的进度条
        this.fakeProgress = 0;
        this.schedule(this.fakeProgressUpdate, 0.02); // 每0.02秒更新一次进度条
    }

    private onProgress(completedCount: number, totalCount: number): void {
        // 计算真实进度
        const realProgress = completedCount / totalCount;
        // 如果真实进度大于假进度，则将假进度同步为真实进度
        if (realProgress > this.fakeProgress) {
            this.fakeProgress = realProgress;
        }
    }

    private fakeProgressUpdate(): void {
        // 控制假的进度条缓慢增长，最大到95%
        if (this.fakeProgress < 0.9) {
            this.fakeProgress += 0.001; // 每次增加1%
        }

        // 更新进度条
        if (this.progressBar) {
            this.progressBar.getComponent(Sprite).fillRange = this.fakeProgress;
        }

        // 当达到1，即加载完成时停止进度更新
        if (this.fakeProgress >= 1) {
            this.unschedule(this.fakeProgressUpdate);
        }
    }

}

